package com.example.exceldemo.liteflowComponent.qh;

import cn.hutool.core.date.DateUtil;
import com.alibaba.excel.util.StringUtils;
import com.deepoove.poi.config.Configure;
import com.example.exceldemo.constants.DocConstants;
import com.example.exceldemo.constants.ReqMgrConstants;
import com.example.exceldemo.liteflowComponent.common.GenerateDocuments;
import com.example.exceldemo.model.DemoContext;
import com.example.exceldemo.model.FunctionInfoDTO;
import com.example.exceldemo.model.ReqAnalysisSpecificationDTO;
import com.example.exceldemo.model.ReqInfoDTO;
import com.example.exceldemo.util.WordUtil;
import com.yomahub.liteflow.annotation.LiteflowComponent;
import lombok.extern.slf4j.Slf4j;

import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 生成需求分析文档  青海
 *
 * @author yangwb8
 * @Date 2025/5/17 04:06
 */
@LiteflowComponent("qh_one")
@Slf4j
public class GenerateQhOneDocuments extends GenerateDocuments {
    @Override
    public void processReqDocuments(ReqInfoDTO reqInfo, String templateDir, String reqOutputDir, Map<String, String> settings) {
        log.info("开始生成需求分析文档");
        //
        ReqAnalysisSpecificationDTO reqAnalysisDTO = prepareReqAnalysisData(reqInfo, settings);
        DemoContext deoContext = getDemoContext();
        deoContext.setReqAnalysisDTO(reqAnalysisDTO);

        Configure baseConfig = createBaseConfig(getPolicy());

        // 修改：直接使用模板文件名，无需构建完整路径
        String templateFileName = ReqMgrConstants.TEMPLATE_ANALYSIS;
        Path outputPath = Paths.get(reqOutputDir, getDocName(reqInfo));
        String provCode = reqInfo.getProvCode();
        // 统一使用类路径方式生成文档
        WordUtil.generateWordFileByOS(provCode, templateFileName, outputPath.toString(), reqAnalysisDTO, baseConfig);
        log.info("需求分析文档生成完成");
    }

    @Override
    public String getDocName(ReqInfoDTO reqInfo) {
        return "青海-BSS-" + DateUtil.format(LocalDateTime.now(), "yyyyMM") + "-" + reqInfo.getReqNo() + "-"
                + reqInfo.getReqName() + "_需求分析说明书.docx";
    }

    /**
     * 准备需求分析说明书数据
     *
     * @param x        需求信息
     * @param settings 配置信息
     * @return 需求分析说明书数据对象
     */
    private ReqAnalysisSpecificationDTO prepareReqAnalysisData(ReqInfoDTO x, Map<String, String> settings) {
        ReqAnalysisSpecificationDTO reqInfo = new ReqAnalysisSpecificationDTO();
        reqInfo.setAuthor(settings.getOrDefault("author", x.getReqDeveloper()));
        reqInfo.setCrtDate(DateUtil.format(LocalDateTime.now(), "yyyy-MM-dd"));
        reqInfo.setVersion(settings.getOrDefault("version", "V1.0"));
        reqInfo.setAuditor(settings.getOrDefault("auditor", "刘锐"));
        reqInfo.setAuditDate(DateUtil.format(LocalDateTime.now(), "yyyy-MM-dd"));

        reqInfo.setReqNo(x.getReqNo());
        reqInfo.setReqName(x.getReqName());
        reqInfo.setReqDesc(x.getReqDesc());
        reqInfo.setAnalysts(settings.getOrDefault("analysts", "马文明"));
        reqInfo.setAnalysisTime(DateUtil.format(LocalDateTime.now(), "yyyy-MM-dd"));
        reqInfo.setReqOwner(x.getReqOwner());
        reqInfo.setReqDeveloper(x.getReqDeveloper());
        reqInfo.setOnlineVersion(x.getOnlineVersion());
        reqInfo.setReqProposeTime(DateUtil.format(x.getReqProposeTime(), "yyyy-MM-dd"));
        reqInfo.setIsKey(settings.getOrDefault("isKey", "否"));
        reqInfo.setUrgency(settings.getOrDefault("urgency", "一般"));
        reqInfo.setExpectOnlineTime(DateUtil.format(x.getExpectOnlineTime(), "yyyy-MM-dd"));

        List<String> modules = Arrays.asList("订单中心");
        reqInfo.setModules(modules.toString());

        reqInfo.setWorkingTotalHours("");
        reqInfo.setIsUrgent(settings.getOrDefault("isUrgent", "否"));

        reqInfo.setFunctionList(this.processFunctionList(x));


        return reqInfo;
    }

    public List<FunctionInfoDTO> processFunctionList(ReqInfoDTO reqInfo) {
// 检查功能列表是否为空，如果为空则添加默认功能
        if (StringUtils.isBlank(reqInfo.getFunctionList())) {
            log.warn("需求 {} 没有功能列表，将使用默认功能", reqInfo.getReqNo());
            reqInfo.setFunctionList(DocConstants.Function.DEFAULT_FUNCTION);
        }
        // 解析并构建功能列表对象
        List<FunctionInfoDTO> functionList = new ArrayList<>();
        String[] functionListStr = reqInfo.getFunctionList().split(DocConstants.Function.SEPARATOR);
        String developer = Optional.ofNullable(reqInfo.getReqDeveloper()).orElse("");

        AtomicInteger counter = new AtomicInteger(1);

        for (String functionStr : functionListStr) {
            if (StringUtils.isBlank(functionStr)) {
                continue;
            }

            String[] funDescs = functionStr.split(DocConstants.Function.DESC_SEPARATOR);
            FunctionInfoDTO functionInfoDTO = new FunctionInfoDTO();

            functionInfoDTO.setCode(String.valueOf(counter.getAndIncrement()));
            functionInfoDTO.setName(functionStr.trim());
            functionInfoDTO.setDesc(functionStr.trim());

            if (funDescs.length > 1) {
                functionInfoDTO.setName(funDescs[0].trim());
                functionInfoDTO.setDesc(funDescs[1].trim());
            }
            functionInfoDTO.setModel("CRM");
            functionInfoDTO.setRenovationDesc(functionStr.trim());
            functionInfoDTO.setSystem("青海NGBOSS");
            functionInfoDTO.setDeveloper(developer);
            functionList.add(functionInfoDTO);
        }

        return functionList;

    }


}
